/**
 * Real Local Image Upload Test
 * 
 * This example demonstrates how to upload your actual local image file
 * and use it with the AI Model Face & Hair Detail Fix template.
 */

import { join } from 'path';
import { ComfyUIClient, aiModelFaceHairFixTemplate } from '../src';

async function testWithRealLocalImage() {
  console.log('🚀 Starting Real Local Image Upload Test');
  
  // Initialize client
  const client = new ComfyUIClient({
    baseUrl: 'http://192.168.0.193:8188'
  });

  try {
    // Connect to ComfyUI server
    console.log('📡 Connecting to ComfyUI server...');
    await client.connect();
    console.log('✅ Connected successfully!');

    // Register the template
    console.log('📝 Registering AI Model Face & Hair Fix template...');
    client.templates.registerFromData(aiModelFaceHairFixTemplate);
    const template = client.templates.getById(aiModelFaceHairFixTemplate.metadata.id);
    
    if (!template) {
      throw new Error('Failed to register template');
    }
    console.log('✅ Template registered!');

    // 您的实际本地图片路径
    const localImagePath = join(__dirname,'../20250808-111737.png');
    
    console.log(`\n📤 Uploading your image: ${localImagePath}`);
    console.log('⏳ This may take a moment depending on file size and network speed...');

    try {
      // 方法1: 分步上传和执行
      console.log('\n🔄 Step 1: Uploading image to ComfyUI server...');
      const uploadedFilename = await client.uploadImageFromPath(localImagePath);
      console.log(`✅ Upload successful! Server filename: ${uploadedFilename}`);

      console.log('\n🔄 Step 2: Executing AI Model Face & Hair Enhancement...');
      const result = await client.executeTemplate(template, {
        input_image: uploadedFilename,
        face_prompt: 'beautiful woman, perfect skin, detailed facial features, professional photography',
        face_denoise: '0.25'
      }, {
        callbacks: {
          onProgress: (progress) => {
            const percentage = Math.round((progress.progress / progress.max) * 100);
            console.log(`⏳ Progress: ${percentage}% (${progress.progress}/${progress.max}) - Node: ${progress.nodeId}`);
          },
          onExecuting: (nodeId) => {
            console.log(`🔄 Executing node: ${nodeId}`);
          },
          onExecuted: (result) => {
            if (result.outputs && Object.keys(result.outputs).length > 0) {
              console.log(`✅ Node completed with outputs`);
            }
          },
          onError: (error) => {
            console.error(`❌ Execution error: ${error.message}`);
          }
        },
        timeout: 180000 // 3 minutes timeout for complex workflow
      });

      if (result.success) {
        console.log('\n🎉 AI Model Enhancement completed successfully!');
        console.log(`📊 Total execution time: ${result.executionTime}ms (${(result.executionTime / 1000).toFixed(1)}s)`);
        console.log(`🆔 Prompt ID: ${result.promptId}`);
        
        if (result.outputs) {
          console.log('\n📁 Generated outputs:');
          console.log(JSON.stringify(result.outputs, null, 2));
          
          // Convert outputs to HTTP URLs
          const imageUrls = client.outputsToUrls(result.outputs);
          console.log('\n🖼️  Enhanced Image URLs:');
          if (Array.isArray(imageUrls)) {
            imageUrls.forEach((url, index) => {
              console.log(`   ${index + 1}. ${url}`);
            });
          } else {
            console.log(`   ${imageUrls}`);
          }
          
          console.log('\n💡 How to use these URLs:');
          console.log('   - Copy the URL and paste in your browser to view');
          console.log('   - Right-click and "Save As" to download');
          console.log('   - Use in your application to display the enhanced image');
        }
      } else {
        console.error('\n❌ AI Model Enhancement failed!');
        console.error('Error details:', result.error?.message);
      }

    } catch (uploadError) {
      console.error(`\n💥 Upload/Execution failed: ${uploadError}`);
      
      if (uploadError instanceof Error) {
        if (uploadError.message.includes('File not found')) {
          console.log('\n💡 Troubleshooting Tips:');
          console.log('1. 🔍 Check if the file path is correct');
          console.log('2. 📁 Make sure the file exists at the specified location');
          console.log('3. 🔐 Ensure you have read permissions for the file');
          console.log('4. 📝 Try using forward slashes: C:/Users/imeep/Downloads/20250808-111737.png');
          console.log('5. 🖼️  Verify the file is a valid image format (PNG, JPG, etc.)');
        } else if (uploadError.message.includes('Failed to upload')) {
          console.log('\n💡 Network/Server Issues:');
          console.log('1. 🌐 Check if ComfyUI server is running and accessible');
          console.log('2. 📡 Verify network connection to the server');
          console.log('3. 💾 Check if server has enough disk space');
          console.log('4. 🔒 Ensure server allows file uploads');
        }
      }
    }

  } catch (error) {
    console.error('\n💥 General error:', error);
  } finally {
    // Disconnect
    console.log('\n🔌 Disconnecting from ComfyUI server...');
    await client.disconnect();
    console.log('👋 Disconnected successfully!');
  }
}

// Alternative method using one-step upload and execute
async function testOneStepMethod() {
  console.log('\n\n🚀 Testing One-Step Method (Upload + Execute)');
  
  const client = new ComfyUIClient({
    baseUrl: 'http://192.168.0.193:8188'
  });

  try {
    await client.connect();
    client.templates.registerFromData(aiModelFaceHairFixTemplate);
    const template = client.templates.getById(aiModelFaceHairFixTemplate.metadata.id);
    
    if (!template) {
      throw new Error('Failed to register template');
    }

    const localImagePath = join(__dirname,'../20250808-111737.png');
    
    console.log('🔄 One-step upload and execute...');
    const result = await client.executeTemplateWithLocalImage(
      template,
      {
        face_prompt: 'stunning model, flawless skin, professional photography, high quality',
        face_denoise: '0.3'
      },
      localImagePath,
      {
        callbacks: {
          onProgress: (progress) => {
            const percentage = Math.round((progress.progress / progress.max) * 100);
            console.log(`⏳ Progress: ${percentage}% - Node: ${progress.nodeId}`);
          }
        },
        timeout: 180000
      }
    );

    if (result.success) {
      console.log('🎉 One-step method completed successfully!');
      const imageUrls = client.outputsToUrls(result.outputs || {});
      console.log('🖼️  Result URLs:', imageUrls);
    }

  } catch (error) {
    console.log(`⚠️  One-step method failed: ${error}`);
  } finally {
    await client.disconnect();
  }
}

// Show usage examples
function showUsageExamples() {
  console.log('\n📚 Complete Usage Guide for Local Images:');
  console.log('');
  console.log('🔧 Basic Setup:');
  console.log('```typescript');
  console.log('import { ComfyUIClient, aiModelFaceHairFixTemplate } from "@roasmax/comfyui";');
  console.log('');
  console.log('const client = new ComfyUIClient({');
  console.log('  baseUrl: "http://your-comfyui-server:8188"');
  console.log('});');
  console.log('```');
  console.log('');
  console.log('📤 Method 1 - Manual Upload:');
  console.log('```typescript');
  console.log('// Upload image first');
  console.log('const filename = await client.uploadImageFromPath(');
  console.log('  "C:\\\\Users\\\\imeep\\\\Downloads\\\\20250808-111737.png"');
  console.log(');');
  console.log('');
  console.log('// Then execute template');
  console.log('const result = await client.executeTemplate(template, {');
  console.log('  input_image: filename,');
  console.log('  face_prompt: "beautiful woman, perfect skin",');
  console.log('  face_denoise: "0.25"');
  console.log('});');
  console.log('```');
  console.log('');
  console.log('🚀 Method 2 - One-Step (Recommended):');
  console.log('```typescript');
  console.log('const result = await client.executeTemplateWithLocalImage(');
  console.log('  template,');
  console.log('  {');
  console.log('    face_prompt: "stunning model, flawless skin",');
  console.log('    face_denoise: "0.3"');
  console.log('  },');
  console.log('  "C:\\\\Users\\\\imeep\\\\Downloads\\\\20250808-111737.png"');
  console.log(');');
  console.log('```');
}

// Run the tests
async function runAllTests() {
  showUsageExamples();
  await testWithRealLocalImage();
  // Uncomment to test one-step method as well
  // await testOneStepMethod();
}

// Execute if run directly
if (require.main === module) {
  runAllTests();
}

export { testWithRealLocalImage, testOneStepMethod, showUsageExamples };
